//
//  AppDelegate.swift
//  HMWeibo06
//
//  Created by apple on 15/5/10.
//  Copyright (c) 2015年 heima. All rights reserved.
//

import UIKit

/// 全局变量定义，放在 class 的外面
var sharedUserAccount = UserAccount.loadUserAccount()
/// 切换根视图控制器的通知
let HMSwitchRootViewControllerNotification = "HMSwitchRootViewControllerNotification"

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?


    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

        // 实例化 window
        window = UIWindow(frame: UIScreen.mainScreen().bounds)
        window?.backgroundColor = UIColor.whiteColor()
        window?.makeKeyAndVisible()
        
        println(sharedUserAccount)
        
        // 设置外观（一经设置，全局有效，外观设置要尽量的早）
        setupAppearance()
    
        // 注册通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "switchRootViewController:", name: HMSwitchRootViewControllerNotification, object: nil)
        
        // 设置主界面
        showMainInterface()
        
        return true
    }
    
    /// 设置外观
    private func setupAppearance() {
        UINavigationBar.appearance().tintColor = UIColor.orangeColor()
        UITabBar.appearance().tintColor = UIColor.orangeColor()
    }
    
    /// 所有根视图控制器的切换工作统一管理
    func switchRootViewController(n: NSNotification) {
        // 从 object 获取要跳转的 sbname
        showStoryboard(n.object as! String)
    }
    
    /// cmd+shift+f
    private func showStoryboard(sbName: String) {
        self.window?.rootViewController = UIStoryboard.initialViewController(sbName)
    }
    
    /// 主界面的流程
    private func showMainInterface() {
        // 判断用户是否登录，如果没有登录，显示 Main
        var sbName = "Main"
        
        if sharedUserAccount != nil {
            sbName = isNewUpdate() ? "NewFeature" : "Welcome"
        }
        
        showStoryboard(sbName)
    }
    
    /// 是否新更新版本
    private func isNewUpdate() -> Bool {

        // 版本信息可以从 MainBundle 的 Info.plist 获取
//        println(NSBundle.mainBundle().infoDictionary)
        let currentVersion = NSBundle.mainBundle().infoDictionary!["CFBundleShortVersionString"] as! String
        let versionValue = NSNumberFormatter().numberFromString(currentVersion)!.doubleValue
        
        // 和沙盒中的版本进行比较
        let sandboxKey = "sandboxKey"
        
        let defaults = NSUserDefaults.standardUserDefaults()
        let sandboxVersion = defaults.doubleForKey(sandboxKey)
        
        // 及时记录最新的版本
        defaults.setDouble(versionValue, forKey: sandboxKey)
        defaults.synchronize()
        
        return versionValue > sandboxVersion
    }
}

